import sqlite3  # 是个第三方库也是一个数据库


class SQLite:
    def __init__(self, db_name):
        self.sql_lite = sqlite3
        self.connect = None
        self.cur = None
        self.db_name = db_name

    @staticmethod
    def precompile(field):
        field_count = field.count(",") + 1
        precompile = "("
        for _ in range(field_count):
            precompile += "?, "
        precompile = precompile[:-2] + ")"
        return precompile

    def connect_db(self):
        self.connect = self.sql_lite.connect(self.db_name)
        self.cur = self.connect.cursor()
        print(f"成功连接到数据库{self.db_name}")

    def create_db(self):
        self.connect(self.db_name)
        print(f"成功创建数据库{self.db_name}")

    def create_table(self, sql_cmd):
        if self.cur:
            self.cur.execute(sql_cmd)
            # 提交
            self.connect.commit()
            print('成功建表')
        else:
            print("数据库未连接")

    def insert_data(self, sql_cmd, data, batch=False):
        # 单条数据
        if batch:
            self.cur.executemany(sql_cmd, data)
        else:
            self.cur.execute(sql_cmd, data)
        self.connect.commit()

    def query_data(self, sql_cmd, name):
        self.cur.execute(sql_cmd, name)
        self.connect.commit()
        return self.cur.fetchall()

    def close_connect(self):
        self.cur.close()
        self.connect.close()
